package cn.mumzone.pos.ui.fragment;

import android.app.Dialog;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.adapter.TextWatcherAdapter;
import cn.mumzone.basic.base.BaseFragment;
import cn.mumzone.basic.dialog.AlertDialog;
import cn.mumzone.basic.loading.button.LoadingButton;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.EditTextUtil;
import cn.mumzone.basic.util.ItemClickSupport;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.NetUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.basic.util.ToastUtil;
import cn.mumzone.pos.R;
import cn.mumzone.pos.dialog.PosAlertDialog;
import cn.mumzone.pos.event.BindMemberEntity;
import cn.mumzone.pos.event.GoodsAmountChangedEvent;
import cn.mumzone.pos.event.MemberChangeEvent;
import cn.mumzone.pos.model.GoodsEntity;
import cn.mumzone.pos.model.MemberEntity;
import cn.mumzone.pos.presenter.CashGoodsPresenter;
import cn.mumzone.pos.presenter.contract.CashGoodsContract;
import cn.mumzone.pos.ui.activity.ACT_MemberDetail;
import cn.mumzone.pos.ui.activity.ACT_SettleAccounts;
import cn.mumzone.pos.ui.adapter.ADA_CartGoods;
import cn.mumzone.pos.ui.adapter.ADA_GoodsSoldList;
import cn.mumzone.pos.ui.widgets.refresh.SmartRefreshLayout;
import cn.mumzone.pos.ui.widgets.refresh.api.RefreshLayout;
import cn.mumzone.pos.ui.widgets.refresh.listener.OnLoadMoreListener;
import cn.mumzone.pos.util.AddMemberUtil;
import cn.mumzone.pos.util.GoodsUtil;
import cn.mumzone.pos.util.LedDisplayUtil;

/**
 * Created by JoeLjt on 2019/7/5.
 * Email: lijiateng1219@gmail.com
 * Description:
 */

public class FRA_CashGoods extends BaseFragment<CashGoodsPresenter> implements CashGoodsContract.View {

    /**
     * 商品收银台 购物车列表
     */
    private final LinkedList<GoodsEntity> mCashCartList = new LinkedList<>();

    @BindView(R.id.et_search_goods)
    EditText etSearchGoods;
    @BindView(R.id.rv_discounted_goods)
    LRecyclerView rvGoodsList;
    @BindView(R.id.ll_empty_goods)
    LinearLayout llEmptyGoods;
    @BindView(R.id.iv_empty_goods)
    AppCompatImageView ivEmptyGoods;
    @BindView(R.id.tv_goods_empty)
    TextView tvGoodsEmpty;
    @BindView(R.id.tv_goods_empty_hint)
    TextView tvGoodsEmptyHint;

    @BindView(R.id.tv_goods_title_info)
    TextView tvTitleGoodsInfo;
    @BindView(R.id.tv_goods_title_search)
    TextView tvTitleSearchResult;

    @BindView(R.id.et_scan)
    EditText etScan;

    @BindView(R.id.rb_search)
    RadioButton rbSearch;

    @BindView(R.id.iv_clear_input)
    AppCompatImageView ivClearInput;

    @BindView(R.id.tv_name_birthday)
    TextView tvNameBirthday;
    @BindView(R.id.tv_phone_birthday)
    TextView tvPhoneBirthday;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_add_member)
    TextView tvAddMember;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_vip)
    TextView tvVip;
    @BindView(R.id.iv_add_or_unbind_member)
    ImageView ivAddOrUnbindMember;

    @BindView(R.id.ll_empty_cart)
    LinearLayout llEmptyCart;
    @BindView(R.id.ll_cart_goods)
    LinearLayout llCartGoods;
    @BindView(R.id.rv_cart_goods)
    LRecyclerView rvCartList;
    @BindView(R.id.tv_select_count)
    TextView tvSelectCount;
    @BindView(R.id.tv_select_price)
    TextView tvSelectPrice;
    @BindView(R.id.btn_settle)
    LoadingButton btnSettle;

    @BindView(R.id.ll_container)
    LinearLayout llContainer;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private AlertDialog mEditGoodsDialog;

    private boolean isGoingToSettle;

    private MemberEntity mSelectMember;

    // 当前是否正在执行扫码，防止过快扫描
    private boolean isScanExecuted;

    private ADA_GoodsSoldList mGoodsAdapter;
    private ADA_CartGoods mCartGoodsAdapter;

    private LedDisplayUtil ledDisplayUtil;

    @Override
    protected void onUserVisible() {
        btnSettle.stopLoading("结账");
        etScan.requestFocus();
    }

    @Override
    protected void initEventAndData() {

        ledDisplayUtil = new LedDisplayUtil(mContext);

        initGoodsRv();

        initCartRv();

        showMemberInfo();

        toggleEmptyLayout(true, true);

        showCartListStatus(true);

        initScanCodeRelated();

        mPresenter.initEvent();

    }

    private void initCartRv() {
        rvCartList.setLayoutManager(new LinearLayoutManager(mContext));
        mCartGoodsAdapter = new ADA_CartGoods(mContext);
        mCartGoodsAdapter.setOnGoodsAmountChangedListener(new ADA_CartGoods.OnGoodsAmountChangedListener() {
            @Override
            public void onAmountChanged(int position) {
                mPresenter.addGoodsToCart(false, mCashCartList);
            }

            @Override
            public void onGoodsDeleted(final int position) {
                new PosAlertDialog.Builder(mContext)
                        .setRemindText("确认要删除商品吗？")
                        .setOnConfirmClickListener(new PosAlertDialog.OnConfirmClickListener() {
                            @Override
                            public void onConfirmClick(View view, Dialog dialog) {
                                GoodsEntity mDeletedEntity = mCartGoodsAdapter.getDataList().get(position - 1);
                                mDeletedEntity.setSelectCount(0);
                                mCashCartList.remove(position - 1);
                                mCartGoodsAdapter.getDataList().remove(position - 1);
                                mCartGoodsAdapter.notifyDataSetChanged();
                                boolean isBindMember = mSelectMember != null && !StringUtils.isEmpty(mSelectMember.getMemberId());
                                GoodsUtil.updateSelectCountAndAmountForGoods(tvSelectCount, tvSelectPrice, mCartGoodsAdapter.getDataList(), isBindMember);
                                if (ListUtil.isListEmpty(mCartGoodsAdapter.getDataList())) {
                                    showCartListStatus(true);
                                }
                                RxBus.getDefault().post(new GoodsAmountChangedEvent(mCashCartList));
                                PosToast.INSTANCE.makeCheckMarkToast(mContext, "已删除");
                                GoodsUtil.updateGoodsSelectStatus(mGoodsAdapter, mGoodsAdapter.getDataList(), mCashCartList);
                            }
                        }).build().show();
            }
        });
        mCartGoodsAdapter.setOnEditGoodsListener(new ADA_CartGoods.OnEditGoodsListener() {
            @Override
            public void onEditGoodsInfo(GoodsEntity entity) {
                mEditGoodsDialog = GoodsUtil.showEditGoodsDialog(mContext, entity, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mPresenter.addGoodsToCart(true, mCashCartList);
                    }
                });
            }

            @Override
            public void onEditGoodsPrice(GoodsEntity entity) {
                AlertDialog dialog = GoodsUtil.showModifyBargainDialog(mContext, null, entity);
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        mPresenter.addGoodsToCart(false, mCashCartList);
                    }
                });
            }
        });
        rvCartList.setAdapter(new LRecyclerViewAdapter(mCartGoodsAdapter));
        rvCartList.setHasFixedSize(true);
        rvCartList.setLoadMoreEnabled(false);
        rvCartList.setPullRefreshEnabled(false);
    }

    private void initGoodsRv() {

        GridLayoutManager manager = new GridLayoutManager(mContext, 3);
        rvGoodsList.setLayoutManager(manager);
        mGoodsAdapter = new ADA_GoodsSoldList(mContext);
        rvGoodsList.setAdapter(new LRecyclerViewAdapter(mGoodsAdapter));
        GridItemDecoration divider = new GridItemDecoration.Builder(mContext)
                .setHorizontal(R.dimen.dp_6)
                .setColorResource(android.R.color.transparent)
                .build();
        rvGoodsList.addItemDecoration(divider);
        rvGoodsList.setHasFixedSize(true);
        rvGoodsList.setPullRefreshEnabled(false);
        rvGoodsList.setLoadMoreEnabled(false);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new cn.mumzone.pos.ui.widgets.refresh.listener.OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                mPresenter.searchGoodsInfo(mSelectMember, etSearchGoods.getText().toString(), true, false);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.searchGoodsInfo(mSelectMember, etSearchGoods.getText().toString(), false, false);
            }
        });
        // click event
        ItemClickSupport.addTo(rvGoodsList).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                List<GoodsEntity> goodsList = mGoodsAdapter.getDataList();
                GoodsEntity selectedEntity = goodsList.get(position - 1);
                if (!StringUtils.isTrue(selectedEntity.getStockGoods())) {
                    doAddGoodsToCart(selectedEntity, null);
                } else {
                    showError("商品未入库，无法售卖~");
                }
            }
        });

    }

    /**
     * 初始化扫码工作
     */
    private void initScanCodeRelated() {

        GoodsUtil.initScanForGoodsSold(mContext, etScan, etSearchGoods, new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String code = v.getText().toString().trim();
                if (actionId == KeyEvent.ACTION_DOWN && !TextUtils.isEmpty(code)) {

                    if (!NetUtil.isNetworkAvailable(mContext)) {
                        PosToast.INSTANCE.makeShortToast(mContext, "网络不给力，请稍候再试");
                        return true;
                    }

                    if (!isScanExecuted) {
                        mPresenter.searchGoodsInfo(mSelectMember, code, true, true);
                    }
                    etScan.setText("");
                    isScanExecuted = true;
                }
                return true;
            }
        }, new TextWatcherAdapter() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                boolean isInputNotEmpty = !TextUtils.isEmpty(etSearchGoods.getText().toString());
                ivClearInput.setVisibility(isInputNotEmpty ? View.VISIBLE : View.GONE);
                rbSearch.setEnabled(isInputNotEmpty);
                rbSearch.setChecked(isInputNotEmpty);
            }
        });
        etSearchGoods.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    EditTextUtil.hideSoftInput(mContext, v);

                    refreshLayout.autoRefresh();
                }
                return false;
            }
        });
    }

    public boolean toggleEmptyLayout(boolean isEmpty, boolean isDataEmpty) {
        if (isEmpty) {
            // 商品信息 + 空页面
            tvTitleGoodsInfo.setVisibility(View.VISIBLE);
            llEmptyGoods.setVisibility(View.VISIBLE);
            // 搜索结果 + 列表
            tvTitleSearchResult.setVisibility(View.GONE);
            rvGoodsList.setVisibility(View.GONE);

            ivEmptyGoods.setImageResource(isDataEmpty ? R.mipmap.ic_cash_service_empty : R.mipmap.ic_cash_service_empty_search);
            tvGoodsEmpty.setText(isDataEmpty ? "暂无商品信息" : "没有找到任何内容");
            tvGoodsEmptyHint.setText(isDataEmpty ? "您可以在后台配置商品信息" : "你可以换个关键词试试~");
            tvGoodsEmptyHint.setTextColor(isDataEmpty ? getResources().getColor(R.color.order_status_service) :
                    getResources().getColor(R.color.content_text_color));
            tvGoodsEmptyHint.setCompoundDrawablesWithIntrinsicBounds(isDataEmpty ?
                            getResources().getDrawable(R.drawable.svg_ic_alert_remind) : null,
                    null, null, null);

        } else {
            // 商品信息 + 空页面
            tvTitleGoodsInfo.setVisibility(View.GONE);
            llEmptyGoods.setVisibility(View.GONE);
            // 搜索结果 + 列表
            tvTitleSearchResult.setVisibility(View.VISIBLE);
            rvGoodsList.setVisibility(View.VISIBLE);
        }
        return isEmpty;
    }

    @OnClick({R.id.tv_goods_title_info, R.id.rb_search, R.id.iv_clear_input,
            R.id.iv_add_or_unbind_member, R.id.rl_member_layout, R.id.btn_settle})
    void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rb_search:
                refreshLayout.autoRefresh();
                break;
            case R.id.iv_clear_input:
                etSearchGoods.setText("");
                mGoodsAdapter.getDataList().clear();
                toggleEmptyLayout(true, true);
                break;
            case R.id.iv_add_or_unbind_member:
                boolean isMemberNull = mSelectMember == null || StringUtils.isEmpty(mSelectMember.getPhone());
                AddMemberUtil.doSthAboutMemberBinding(mContext, isMemberNull, mPresenter, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mSelectMember = null;
                        showMemberInfo();
                        RxBus.getDefault().post(new MemberChangeEvent(mSelectMember));
                        PosAlertDialog alertDialog = (PosAlertDialog) dialog;
                        alertDialog.cancelLoading();
                        PosToast.INSTANCE.makeCheckMarkToast(mContext, "已解绑");
                    }
                });
                break;
            case R.id.rl_member_layout:
                if (mSelectMember != null && !StringUtils.isEmpty(mSelectMember.getMemberId()) && !StringUtils.isEmpty(mSelectMember.getPhone())) {
                    ACT_MemberDetail.startAc(mContext, mSelectMember.getMemberId(), mSelectMember.getPhone());

                } else {
                    AddMemberUtil.showSelectMemberDialog(mContext, mPresenter);
                }
                break;
            case R.id.btn_settle:

                // 判断当前购物车有无寄存商品，如果有寄存商品，但是没有绑定会员的，弹窗要求绑定会员
                if (checkGoodsRegisterStatus() && mSelectMember == null) {
                    isGoingToSettle = true;
                    AddMemberUtil.showSelectMemberDialog(mContext, mPresenter);
                    return;
                }

                btnSettle.startLoading("生成账单");
                ACT_SettleAccounts.startAc(mContext,
                        mSelectMember == null ? "" : StringUtils.get(mSelectMember.getPhone()),
                        JSON.toJSONString(mCartGoodsAdapter.getDataList()),
                        ACT_SettleAccounts.SETTLE_ORDER_TYPE_GOODS, false);
                break;
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.fra_cash_goods;
    }

    @Override
    public void showSearchGoodsList(List<GoodsEntity> entitys, boolean isRefresh) {

        GoodsUtil.syncLocalAndRemotePrice(entitys, mCashCartList);
        mCartGoodsAdapter.notifyDataSetChanged();
        boolean isBindMember = mSelectMember != null && !StringUtils.isEmpty(mSelectMember.getMemberId());
        GoodsUtil.updateSelectCountAndAmountForGoods(tvSelectCount, tvSelectPrice, mCartGoodsAdapter.getDataList(), isBindMember);


        // 当前搜索结果来自扫码
        if (isScanExecuted) {

            // 重置扫码状态，允许再次扫码
            isScanExecuted = false;

            if (ListUtil.isListEmpty(entitys)) {
                ToastUtil.makeText(mContext, "未搜索到该商品", false);
            } else if (entitys.size() == 1) {
                doAddGoodsToCart(null, entitys);
            } else {
                GoodsUtil.showGoodsSelectDialog(mContext, mSelectMember != null && !StringUtils.isEmpty(mSelectMember.getMemberId()),
                        mCashCartList, entitys, new GoodsUtil.OnSelectedMultipleGoodsListener() {
                            @Override
                            public void OnSelectedMultipleGoods(List<GoodsEntity> selectedList) {
                                doAddGoodsToCart(null, selectedList);
                            }
                        });
            }

            return;
        }

        // 停止刷新
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();

        // 搜索结果来自于手动搜索，支持刷新和加载
        if (!toggleEmptyLayout(ListUtil.isListEmpty(entitys), true)) {

            // 匹配购物车中已有数据，将已选角标数量反显
            for (GoodsEntity cartGoodsEntity : mCashCartList) {
                for (GoodsEntity requestGoodsEntity : entitys) {
                    if (requestGoodsEntity.getGoodsSkuId().equals(cartGoodsEntity.getGoodsSkuId())) {
                        requestGoodsEntity.setSelectCount(cartGoodsEntity.getSelectCount());
                        break;
                    }
                }
            }

            mGoodsAdapter.update(entitys, isRefresh);
        }

    }

    @Override
    public void showAddGoodsSuccess(boolean isModify) {

        if (isModify) {
            PosToast.INSTANCE.makeCheckMarkToast(mContext, "已修改");
            mEditGoodsDialog.dismiss();
        }

        showCartListStatus(ListUtil.isListEmpty(mCashCartList));
        mCartGoodsAdapter.update(mCashCartList, true);
        boolean isBindMember = mSelectMember != null && !StringUtils.isEmpty(mSelectMember.getMemberId());
        GoodsUtil.updateSelectCountAndAmountForGoods(tvSelectCount, tvSelectPrice, mCartGoodsAdapter.getDataList(), isBindMember);
        GoodsUtil.updateGoodsSelectStatus(mGoodsAdapter, mGoodsAdapter.getDataList(), mCashCartList);

    }

    @Override
    public void showClearCart() { /* 暂时没有清空购物车功能 */ }

    @Override
    public void onGoodsAmountChanged(List<GoodsEntity> cartList) { /* 商品收银台，添加商品到购物车在此处完成，因此不需要这个 RxBus回调 */ }

    @Override
    public void showAddMemberSuccess(MemberEntity memberEntity) {

        this.mSelectMember = memberEntity;
        this.mSelectMember.setMemberId(memberEntity.getId());
        showMemberInfo();

        PosToast.INSTANCE.makeToast(mContext, PosToast.ToastType.TOAST_TYPE_SQUARE,
                PosToast.ToastSquareLevel.ALERT_SUCCESS_SQUARE, "添加成功~", false);

        RxBus.getDefault().post(new BindMemberEntity());
        mGoodsAdapter.notifyDataSetChanged();
        mCartGoodsAdapter.notifyDataSetChanged();
    }

    @Override
    public void showSettleSuccess() {

        etSearchGoods.setText("");
        mSelectMember = null;
        showMemberInfo();

        mCashCartList.clear();
        mCartGoodsAdapter.update(mCashCartList, true);
        boolean isBindMember = mSelectMember != null && !StringUtils.isEmpty(mSelectMember.getMemberId());
        GoodsUtil.updateSelectCountAndAmountForGoods(tvSelectCount, tvSelectPrice, mCashCartList, isBindMember);
        toggleEmptyLayout(true, true);

        PosToast.INSTANCE.makeToast(mContext, PosToast.ToastType.TOAST_TYPE_SQUARE,
                PosToast.ToastSquareLevel.ALERT_SUCCESS_SQUARE, "结账成功！", false);
    }

    @Override
    public void showSearchMemberSuccess(MemberEntity memberEntity) {
        this.mSelectMember = memberEntity;
        RxBus.getDefault().post(new MemberChangeEvent(mSelectMember));
        RxBus.getDefault().post(new BindMemberEntity());
        showMemberInfo();

        PosToast.INSTANCE.makeCheckMarkToast(mContext, "已绑定");

        if (isGoingToSettle) { // 跳转结账
            btnSettle.startLoading("生成账单");
            ACT_SettleAccounts.startAc(mContext, mSelectMember == null ? "" : StringUtils.get(mSelectMember.getPhone()), JSON.toJSONString(mCartGoodsAdapter.getDataList()), ACT_SettleAccounts.SETTLE_ORDER_TYPE_GOODS, false);
            isGoingToSettle = false;
        }
    }

    /**
     * 将选中的 GoodsEntity 添加到购物车
     *
     * @param entity
     * @param list
     */
    private void doAddGoodsToCart(GoodsEntity entity, List<GoodsEntity> list) {
        List<GoodsEntity> postList = GoodsUtil.prepareToAddGoodsToCart(mContext, mCashCartList, entity, list);
        if (!ListUtil.isListEmpty(postList)) {
            ledDisplayUtil.displayPrice(mSelectMember != null && !StringUtils.isEmpty(mSelectMember.getMemberId()) ?
                    StringUtils.get(postList.get(0).getMemberPrice(), postList.get(0).getPrice()) : postList.get(0).getPrice());
            GoodsUtil.updateLocalCartList(mCashCartList, postList);
            mPresenter.addGoodsToCart(false, postList);
        }
    }

    private void showCartListStatus(boolean isListNull) {
        llCartGoods.setVisibility(isListNull ? View.GONE : View.VISIBLE);
        llEmptyCart.setVisibility(isListNull ? View.VISIBLE : View.GONE);
        btnSettle.setEnabled(!isListNull);
    }

    private void showMemberInfo() {
        tvAddMember.setVisibility(mSelectMember == null || StringUtils.isEmpty(mSelectMember.getPhone()) ? View.VISIBLE : View.INVISIBLE);
        tvVip.setVisibility(mSelectMember != null && !StringUtils.isEmpty(mSelectMember.getMemberId()) ? View.VISIBLE : View.INVISIBLE);

        if (mSelectMember != null && !StringUtils.isEmpty(mSelectMember.getMemberId())) {
            if (!StringUtils.isEmpty(mSelectMember.getBirthday()) && AppDateUtil.isBirthdayDay(new Date(),
                    AppDateUtil.timeStamp2Date(mSelectMember.getBirthday()))) {
                tvName.setVisibility(View.INVISIBLE);
                tvPhone.setVisibility(View.INVISIBLE);
                tvNameBirthday.setVisibility(View.VISIBLE);
                tvPhoneBirthday.setVisibility(View.VISIBLE);
                tvBirthday.setVisibility(View.VISIBLE);
            } else {
                tvName.setVisibility(View.VISIBLE);
                tvPhone.setVisibility(View.VISIBLE);
                tvNameBirthday.setVisibility(View.INVISIBLE);
                tvPhoneBirthday.setVisibility(View.INVISIBLE);
                tvBirthday.setVisibility(View.INVISIBLE);
            }
        } else {
            tvName.setVisibility(View.INVISIBLE);
            tvPhone.setVisibility(View.INVISIBLE);
            tvNameBirthday.setVisibility(View.INVISIBLE);
            tvPhoneBirthday.setVisibility(View.INVISIBLE);
            tvBirthday.setVisibility(View.INVISIBLE);

        }

        mCartGoodsAdapter.setBindMember(mSelectMember);
        mCartGoodsAdapter.notifyDataSetChanged();
        mGoodsAdapter.setBindMember(mSelectMember);
        mGoodsAdapter.notifyDataSetChanged();

        if (mSelectMember == null || StringUtils.isEmpty(mSelectMember.getPhone())) {
            ivAddOrUnbindMember.setImageResource(R.drawable.svg_ic_add_member);
        } else {
            tvPhone.setText(StringUtils.getString(mSelectMember.getPhone()));
            tvPhoneBirthday.setText(StringUtils.getString(mSelectMember.getPhone()));
            ivAddOrUnbindMember.setImageResource(R.drawable.svg_ic_open_order_link);
            if (mSelectMember != null && !StringUtils.isEmpty(mSelectMember.getMemberId())) {
                tvName.setTextColor(getResources().getColor(R.color.member_color));
                tvNameBirthday.setTextColor(getResources().getColor(R.color.member_color));
                tvPhone.setTextColor(getResources().getColor(R.color.member_color));
                tvPhoneBirthday.setTextColor(getResources().getColor(R.color.member_color));
                tvName.setText(StringUtils.isEmpty(mSelectMember.getName()) ?
                        "暂无姓名" : StringUtils.getString(mSelectMember.getName()));
                tvNameBirthday.setText(StringUtils.isEmpty(mSelectMember.getName()) ?
                        "暂无姓名" : StringUtils.getString(mSelectMember.getName()));
            } else {
                tvName.setTextColor(getResources().getColor(R.color.white_color));
                tvNameBirthday.setTextColor(getResources().getColor(R.color.white_color));
                tvPhone.setTextColor(getResources().getColor(R.color.white_color));
                tvPhoneBirthday.setTextColor(getResources().getColor(R.color.white_color));
                tvName.setText(StringUtils.isEmpty(mSelectMember.getName()) ?
                        "散客" : StringUtils.getString(mSelectMember.getName()));
                tvNameBirthday.setText(StringUtils.isEmpty(mSelectMember.getName()) ?
                        "散客" : StringUtils.getString(mSelectMember.getName()));
            }
        }

        boolean isBindMember = mSelectMember != null && !StringUtils.isEmpty(mSelectMember.getMemberId());
        GoodsUtil.updateSelectCountAndAmountForGoods(tvSelectCount, tvSelectPrice, mCartGoodsAdapter.getDataList(), isBindMember);

    }

    /**
     * 购物车列表是否有寄存商品，有的话需要强制绑定会员
     *
     * @return
     */
    private boolean checkGoodsRegisterStatus() {
        for (GoodsEntity entity : mCashCartList) {
            if (!StringUtils.isEmpty(entity.getRegisterCount()) && Integer.parseInt(entity.getRegisterCount()) > 0) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void showSearchGoodsError(String msg) {
        if (isScanExecuted) {
            isScanExecuted = false;
            PosToast.INSTANCE.makeShortToast(mContext, msg);
            return;
        }

        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
        }

        toggleEmptyLayout(true, false);
    }

    @Override
    public void showError(String msg) {
        if (isScanExecuted) {
            isScanExecuted = false;
        }
        super.showError(msg);
        if (isScanExecuted) {
            isScanExecuted = false;
        }

        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
        }
    }

    @Override
    public void showNetError() {
        refreshLayout.finishRefresh();
        showNetErrorEmpty(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FRA_CashGoods.super.toggleCloseEmpty();
                refreshLayout.autoRefresh();
            }
        });
    }

    @Override
    protected View getTargetView() {
        return llContainer;
    }
}
